package com.spring.mongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lenovo on 2016/7/24.
 */
@Component
public class Redis {
    private StringRedisTemplate template;

    @Autowired
    public Redis(StringRedisTemplate template) {
        this.template = template;
    }

    public boolean set(List<Map<String, Object>> list) {
        boolean result = template.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection)
                    throws DataAccessException {
                RedisSerializer<String> serializer = template.getStringSerializer();
                for (Map<String, Object> map : list) {
                    String key = map.keySet().iterator().next().toString();
                    String value = map.values().iterator().next().toString();
                    byte[] keys = serializer.serialize(key);
                    byte[] values = serializer.serialize(value);
                    connection.set(keys, values);
                }
                return true;
            }
        }, false, true);
        return result;
    }

    public List<String> get(List<String> key) {
        final RedisSerializer<String> serializer = template.getStringSerializer();
        List<String> result = template.execute(new RedisCallback<List<String>>() {
            @Override
            public List<String> doInRedis(RedisConnection conn)
                    throws DataAccessException {
                List<String> res = new ArrayList<String>();
                for (String k : key) {
                    byte[] keys = serializer.serialize(k);
                    byte[] values = conn.get(keys);
                    String value = serializer.deserialize(values);
                    res.add(value);
                }
                return res;
            }
        });
        return result;
    }
}
